package com.java.IO.file_stream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;

public class FileReaderAPI {
    // 读取纯文本类型文件内的所有内容
    public static StringBuilder readAllContentsOfFile(String path) throws Exception {
        try (FileReader fileReader = new FileReader(path)) {
            StringBuilder resultChars = new StringBuilder();
            
            int length = 0;
            char[] buffer = new char[1024];
            while ((length = fileReader.read(buffer)) != -1) {
                resultChars.append(buffer, 0, length);
            }
            return resultChars;
        } catch (FileNotFoundException e) {
            throw new Exception("路径错误，请检查路径是否存在或正确。错误信息为" + e.getMessage());
        }
    }
    
    public static void main(String[] args) throws Exception {
        String path = "File和IO流\\com\\java\\files\\char_stream.txt";
        
        // 创建对象：若父级路径不存在或文件不存在则抛出异常FileNotFoundException
        FileReader fileReader1 = new FileReader(path);
        FileReader fileReader2 = new FileReader(new File(path));
        
        // read：读取本地文件内数据，若无参数则一次读取一字符，若无数据则返回-1。若参数为字符数组且有数据则一次性读取字符数组长度的字符并存于该字符数组内同时返回读取到的字符长度
        System.out.println(fileReader1.read()); // 97
        System.out.println(fileReader1.read()); // 57
        System.out.println(fileReader1.read()); // 20013 (十进制数)
        System.out.println((char) fileReader1.read()); // 中 (强转)
        System.out.println(fileReader1.read()); // 13
        System.out.println(fileReader1.read()); // 10
        char[] chars = new char[20];
        System.out.println(fileReader1.read(chars, 13, 2)); // 2
        System.out.println(Arrays.toString(chars)); // [ ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  , a, 哈,  ,  ,  ,  ,  ] (读取2个数据到数组指定位置13)
        System.out.println(fileReader1.read(chars)); // 14
        System.out.println(Arrays.toString(chars)); // [c, d, d, e, 啊, 啊, 啊, H, e, l, l, o, H, e, 哈,  ,  ,  ,  ,  ] (残留数据哈)
        System.out.println(fileReader1.read(chars)); // -1
        System.out.println(Arrays.toString(chars)); // [c, d, d, e, 啊, 啊, 啊, H, e, l, l, o, H, e, 哈,  ,  ,  ,  ,  ] (全都是残留数据)
        System.out.println(fileReader1.read()); // -1
        
        // close：关闭流并释放资源
        fileReader1.close();
        fileReader2.close();
        
        // 读取文件内的所有内容，路径必须为文件路径
        System.out.println(readAllContentsOfFile(path)); // a9中中\r\na哈cdde啊啊啊HelloHe
    }
}
